﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using Pharmacy.Entities;
using Pharmacy.Data;

#endregion

namespace Pharmacy.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="PoProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class PoProviderBaseCore : EntityProviderBase<Pharmacy.Entities.Po, Pharmacy.Entities.PoKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, Pharmacy.Entities.PoKey key)
		{
			return Delete(transactionManager, key.PoId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_poId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.String _poId)
		{
			return Delete(null, _poId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_poId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.String _poId);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
	
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		FK_PO_WebUser Description: 
		/// </summary>
		/// <param name="_requestBy"></param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		public TList<Po> GetByRequestBy(System.String _requestBy)
		{
			int count = -1;
			return GetByRequestBy(_requestBy, 0,int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		FK_PO_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_requestBy"></param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		/// <remarks></remarks>
		public TList<Po> GetByRequestBy(TransactionManager transactionManager, System.String _requestBy)
		{
			int count = -1;
			return GetByRequestBy(transactionManager, _requestBy, 0, int.MaxValue, out count);
		}
		
			/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		FK_PO_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_requestBy"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		public TList<Po> GetByRequestBy(TransactionManager transactionManager, System.String _requestBy, int start, int pageLength)
		{
			int count = -1;
			return GetByRequestBy(transactionManager, _requestBy, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		fkPoWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_requestBy"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		public TList<Po> GetByRequestBy(System.String _requestBy, int start, int pageLength)
		{
			int count =  -1;
			return GetByRequestBy(null, _requestBy, start, pageLength,out count);	
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		fkPoWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_requestBy"></param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		public TList<Po> GetByRequestBy(System.String _requestBy, int start, int pageLength,out int count)
		{
			return GetByRequestBy(null, _requestBy, start, pageLength, out count);	
		}
						
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PO_WebUser key.
		///		FK_PO_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_requestBy"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Po objects.</returns>
		public abstract TList<Po> GetByRequestBy(TransactionManager transactionManager, System.String _requestBy, int start, int pageLength, out int count);
		
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override Pharmacy.Entities.Po Get(TransactionManager transactionManager, Pharmacy.Entities.PoKey key, int start, int pageLength)
		{
			return GetByPoId(transactionManager, key.PoId, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_PO index.
		/// </summary>
		/// <param name="_poId"></param>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public Pharmacy.Entities.Po GetByPoId(System.String _poId)
		{
			int count = -1;
			return GetByPoId(null,_poId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PO index.
		/// </summary>
		/// <param name="_poId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public Pharmacy.Entities.Po GetByPoId(System.String _poId, int start, int pageLength)
		{
			int count = -1;
			return GetByPoId(null, _poId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_poId"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public Pharmacy.Entities.Po GetByPoId(TransactionManager transactionManager, System.String _poId)
		{
			int count = -1;
			return GetByPoId(transactionManager, _poId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_poId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public Pharmacy.Entities.Po GetByPoId(TransactionManager transactionManager, System.String _poId, int start, int pageLength)
		{
			int count = -1;
			return GetByPoId(transactionManager, _poId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PO index.
		/// </summary>
		/// <param name="_poId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public Pharmacy.Entities.Po GetByPoId(System.String _poId, int start, int pageLength, out int count)
		{
			return GetByPoId(null, _poId, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_poId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Po"/> class.</returns>
		public abstract Pharmacy.Entities.Po GetByPoId(TransactionManager transactionManager, System.String _poId, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#region _PO_NotComplete 
		
		/// <summary>
		///	This method wrap the '_PO_NotComplete' stored procedure. 
		/// </summary>
		/// <param name="fromdate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="todate"> A <c>System.DateTime?</c> instance.</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="DataSet"/> instance.</returns>
		public DataSet NotComplete(System.DateTime? fromdate, System.DateTime? todate)
		{
			return NotComplete(null, 0, int.MaxValue , fromdate, todate);
		}
		
		/// <summary>
		///	This method wrap the '_PO_NotComplete' stored procedure. 
		/// </summary>
		/// <param name="fromdate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="todate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="DataSet"/> instance.</returns>
		public DataSet NotComplete(int start, int pageLength, System.DateTime? fromdate, System.DateTime? todate)
		{
			return NotComplete(null, start, pageLength , fromdate, todate);
		}
				
		/// <summary>
		///	This method wrap the '_PO_NotComplete' stored procedure. 
		/// </summary>
		/// <param name="fromdate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="todate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="DataSet"/> instance.</returns>
		public DataSet NotComplete(TransactionManager transactionManager, System.DateTime? fromdate, System.DateTime? todate)
		{
			return NotComplete(transactionManager, 0, int.MaxValue , fromdate, todate);
		}
		
		/// <summary>
		///	This method wrap the '_PO_NotComplete' stored procedure. 
		/// </summary>
		/// <param name="fromdate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="todate"> A <c>System.DateTime?</c> instance.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="DataSet"/> instance.</returns>
		public abstract DataSet NotComplete(TransactionManager transactionManager, int start, int pageLength , System.DateTime? fromdate, System.DateTime? todate);
		
		#endregion
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;Po&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;Po&gt;"/></returns>
		public static TList<Po> Fill(IDataReader reader, TList<Po> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				Pharmacy.Entities.Po c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("Po")
					.Append("|").Append((System.String)reader[((int)PoColumn.PoId - 1)]).ToString();
					c = EntityManager.LocateOrCreate<Po>(
					key.ToString(), // EntityTrackingKey
					"Po",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new Pharmacy.Entities.Po();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.PoId = (System.String)reader[((int)PoColumn.PoId - 1)];
					c.OriginalPoId = c.PoId;
					c.PoDate = (System.DateTime)reader[((int)PoColumn.PoDate - 1)];
					c.RequestBy = (System.String)reader[((int)PoColumn.RequestBy - 1)];
					c.DeliveryTo = (reader.IsDBNull(((int)PoColumn.DeliveryTo - 1)))?null:(System.String)reader[((int)PoColumn.DeliveryTo - 1)];
					c.Remark = (reader.IsDBNull(((int)PoColumn.Remark - 1)))?null:(System.String)reader[((int)PoColumn.Remark - 1)];
					c.IsComplete = (System.Boolean)reader[((int)PoColumn.IsComplete - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="Pharmacy.Entities.Po"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Po"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, Pharmacy.Entities.Po entity)
		{
			if (!reader.Read()) return;
			
			entity.PoId = (System.String)reader[((int)PoColumn.PoId - 1)];
			entity.OriginalPoId = (System.String)reader["POId"];
			entity.PoDate = (System.DateTime)reader[((int)PoColumn.PoDate - 1)];
			entity.RequestBy = (System.String)reader[((int)PoColumn.RequestBy - 1)];
			entity.DeliveryTo = (reader.IsDBNull(((int)PoColumn.DeliveryTo - 1)))?null:(System.String)reader[((int)PoColumn.DeliveryTo - 1)];
			entity.Remark = (reader.IsDBNull(((int)PoColumn.Remark - 1)))?null:(System.String)reader[((int)PoColumn.Remark - 1)];
			entity.IsComplete = (System.Boolean)reader[((int)PoColumn.IsComplete - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="Pharmacy.Entities.Po"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Po"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, Pharmacy.Entities.Po entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.PoId = (System.String)dataRow["POId"];
			entity.OriginalPoId = (System.String)dataRow["POId"];
			entity.PoDate = (System.DateTime)dataRow["PODate"];
			entity.RequestBy = (System.String)dataRow["RequestBy"];
			entity.DeliveryTo = Convert.IsDBNull(dataRow["DeliveryTo"]) ? null : (System.String)dataRow["DeliveryTo"];
			entity.Remark = Convert.IsDBNull(dataRow["Remark"]) ? null : (System.String)dataRow["Remark"];
			entity.IsComplete = (System.Boolean)dataRow["IsComplete"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Po"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">Pharmacy.Entities.Po Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, Pharmacy.Entities.Po entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;

			#region RequestBySource	
			if (CanDeepLoad(entity, "WebUser|RequestBySource", deepLoadType, innerList) 
				&& entity.RequestBySource == null)
			{
				object[] pkItems = new object[1];
				pkItems[0] = entity.RequestBy;
				WebUser tmpEntity = EntityManager.LocateEntity<WebUser>(EntityLocator.ConstructKeyFromPkItems(typeof(WebUser), pkItems), DataRepository.Provider.EnableEntityTracking);
				if (tmpEntity != null)
					entity.RequestBySource = tmpEntity;
				else
					entity.RequestBySource = DataRepository.WebUserProvider.GetByUserId(transactionManager, entity.RequestBy);		
				
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'RequestBySource' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.RequestBySource != null)
				{
					innerList.SkipChildren = true;
					DataRepository.WebUserProvider.DeepLoad(transactionManager, entity.RequestBySource, deep, deepLoadType, childTypes, innerList);
					innerList.SkipChildren = false;
				}
					
			}
			#endregion RequestBySource
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByPoId methods when available
			
			#region GrnCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<Grn>|GrnCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'GrnCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.GrnCollection = DataRepository.GrnProvider.GetByPoId(transactionManager, entity.PoId);

				if (deep && entity.GrnCollection.Count > 0)
				{
					deepHandles.Add("GrnCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<Grn>) DataRepository.GrnProvider.DeepLoad,
						new object[] { transactionManager, entity.GrnCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region PoDetailsCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<PoDetails>|PoDetailsCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'PoDetailsCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.PoDetailsCollection = DataRepository.PoDetailsProvider.GetByPoId(transactionManager, entity.PoId);

				if (deep && entity.PoDetailsCollection.Count > 0)
				{
					deepHandles.Add("PoDetailsCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<PoDetails>) DataRepository.PoDetailsProvider.DeepLoad,
						new object[] { transactionManager, entity.PoDetailsCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the Pharmacy.Entities.Po object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">Pharmacy.Entities.Po instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">Pharmacy.Entities.Po Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, Pharmacy.Entities.Po entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			
			#region RequestBySource
			if (CanDeepSave(entity, "WebUser|RequestBySource", deepSaveType, innerList) 
				&& entity.RequestBySource != null)
			{
				DataRepository.WebUserProvider.Save(transactionManager, entity.RequestBySource);
				entity.RequestBy = entity.RequestBySource.UserId;
			}
			#endregion 
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
	
			#region List<Grn>
				if (CanDeepSave(entity.GrnCollection, "List<Grn>|GrnCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(Grn child in entity.GrnCollection)
					{
						if(child.PoIdSource != null)
						{
							child.PoId = child.PoIdSource.PoId;
						}
						else
						{
							child.PoId = entity.PoId;
						}

					}

					if (entity.GrnCollection.Count > 0 || entity.GrnCollection.DeletedItems.Count > 0)
					{
						//DataRepository.GrnProvider.Save(transactionManager, entity.GrnCollection);
						
						deepHandles.Add("GrnCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< Grn >) DataRepository.GrnProvider.DeepSave,
							new object[] { transactionManager, entity.GrnCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
	
			#region List<PoDetails>
				if (CanDeepSave(entity.PoDetailsCollection, "List<PoDetails>|PoDetailsCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(PoDetails child in entity.PoDetailsCollection)
					{
						if(child.PoIdSource != null)
						{
							child.PoId = child.PoIdSource.PoId;
						}
						else
						{
							child.PoId = entity.PoId;
						}

					}

					if (entity.PoDetailsCollection.Count > 0 || entity.PoDetailsCollection.DeletedItems.Count > 0)
					{
						//DataRepository.PoDetailsProvider.Save(transactionManager, entity.PoDetailsCollection);
						
						deepHandles.Add("PoDetailsCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< PoDetails >) DataRepository.PoDetailsProvider.DeepSave,
							new object[] { transactionManager, entity.PoDetailsCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region PoChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>Pharmacy.Entities.Po</c>
	///</summary>
	public enum PoChildEntityTypes
	{
		
		///<summary>
		/// Composite Property for <c>WebUser</c> at RequestBySource
		///</summary>
		[ChildEntityType(typeof(WebUser))]
		WebUser,
	
		///<summary>
		/// Collection of <c>Po</c> as OneToMany for GrnCollection
		///</summary>
		[ChildEntityType(typeof(TList<Grn>))]
		GrnCollection,

		///<summary>
		/// Collection of <c>Po</c> as OneToMany for PoDetailsCollection
		///</summary>
		[ChildEntityType(typeof(TList<PoDetails>))]
		PoDetailsCollection,
	}
	
	#endregion PoChildEntityTypes
	
	#region PoFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;PoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Po"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PoFilterBuilder : SqlFilterBuilder<PoColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PoFilterBuilder class.
		/// </summary>
		public PoFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PoFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PoFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PoFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PoFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PoFilterBuilder
	
	#region PoParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;PoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Po"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PoParameterBuilder : ParameterizedSqlFilterBuilder<PoColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PoParameterBuilder class.
		/// </summary>
		public PoParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PoParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PoParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PoParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PoParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PoParameterBuilder
	
	#region PoSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;PoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Po"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class PoSortBuilder : SqlSortBuilder<PoColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PoSqlSortBuilder class.
		/// </summary>
		public PoSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion PoSortBuilder
	
} // end namespace
